using System;
using System.Data;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using Microsoft.TeamFoundation.WebAccess.UI;
using Microsoft.TeamFoundation.WebAccess.Controls;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace Stratman.Web.VSTS.UI.Pages.Timesheet
{
    /// <summary>
    /// Displays an administration page allowing the user to browse the timesheets of all users in the system or
    /// jump directly to timesheets that are waiting to be approved.
    /// </summary>
    public partial class Admin : WebAccessPage
    {
        /// <summary>
        /// Initializes the various members of the class.
        /// </summary>
        /// <param name="e">
        /// Arguments associated with this event.
        /// </param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ActiveTab = "Timesheet";
        }

        /// <summary>
        /// Create a list of breadcrumb hyperlinks that will be displayed above the toolbar.
        /// </summary>
        /// <returns>
        /// A hyperlink pointing to home (Index.aspx)
        /// </returns>
        protected override IEnumerable<BreadCrumbSegment> CreatePageBreadCrumb()
        {
            return (IsUserAdministrator(Request.LogonUserIdentity.Name) ? new BreadCrumbSegment[] { CreateBreadcrumbSegment("Timesheet Administration", null), CreateBreadcrumbSegment("Home", "/Index.aspx") } :
                new BreadCrumbSegment[] { CreateBreadcrumbSegment("Home", "/Index.aspx") });
        }

        private BreadCrumbSegment CreateBreadcrumbSegment(string name, string url)
        {
            return string.IsNullOrEmpty(url) ? new BreadCrumbSegment(name) :
            new BreadCrumbSegment(name, this.Locator.CreateLinkUrl(base.ResolveUrl("~/Index.aspx"), string.Empty, new object[0]));
        }
 

        /// <summary>
        /// Create the buttons to display in the toolbar.
        /// </summary>
        /// <returns>
        /// A button allowing the user to visit their personal timesheet.
        /// </returns>
        protected override StaticMenu CreatePageToolbar()
        {

            if (IsUserAdministrator(Request.LogonUserIdentity.Name))
            {
                StaticMenu toolbar = ToolbarFactory.CreateToolbar(this, this, new ToolbarItems[] {ToolbarItems.EditQuery});

                toolbar.Items[0].Text = "&nbsp;My Timesheet";
                toolbar.Items[0].Action = "parent.location='Explorer.aspx'";

                return toolbar;
            }

            else
                return null;
        }

        /// <summary>
        /// Perform any necessary rendering actions for the page, including creating the toolbar.
        /// </summary>
        protected override void RenderPage()
        {
            ContentTitle = "Timesheet Administration";
        }

        /// <summary>
        /// Event handler that is invoked when the page is loaded; here we get a list timesheets awaiting approval
        /// and write the information to a bulleted list.
        /// </summary>
        /// <param name="sender">
        /// Object from which this event originated.
        /// </param>
        /// <param name="e">
        /// Arguments associated with this event.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Check to make sure that the user is an administrator before giving them access
            if (!IsUserAdministrator(Request.LogonUserIdentity.Name))
            {
                problemsPanel.Visible = true;
                contentPanel.Visible = false;
                problemsLiteral.Text = "You do not have access to the timesheet administrative features.";

                return;
            }

            // Get a list of timesheets awaiting approval
            SqlConnection databaseConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["TimesheetDatabase"].ConnectionString);
            SqlCommand command = new SqlCommand("usp_RS_AwaitingApproval", databaseConnection);

            command.CommandType = CommandType.StoredProcedure;
            databaseConnection.Open();
            lit1.Text += "<ul>";

            SqlDataReader reader = command.ExecuteReader();
            string currentSid = "";

            while (reader.Read())
            {
                // Emit a nested, bulleted list containing a parent bullet for each user and then children for the
                // timesheets that are awaiting approval
                string sid = (string)reader["sid"];
                string displayName = (string)reader["displayName"];
                DateTime weekStarting = (DateTime)reader["weekStarting"];

                if (sid != currentSid)
                {
                    if (currentSid != "")
                        lit1.Text += "</ul></li>";

                    lit1.Text += "<li><a href=\"Explorer.aspx?u=" + sid + "\">" + displayName + "</a><ul>";
                    currentSid = sid;
                }

                lit1.Text += "<li><a href=\"Explorer.aspx?u=" + sid + "&ws=" + weekStarting.ToString("yyyy-MM-dd") + "\">" + weekStarting.ToString("MM/dd/yyyy") + "</a></li>";
            }

            if (currentSid != "")
                lit1.Text += "</ul></li>";

            lit1.Text += "</ul>";
            reader.Close();

            command = new SqlCommand("usp_RS_Users", databaseConnection);
            command.CommandType = CommandType.StoredProcedure;

            reader = command.ExecuteReader();

            lit2.Text += "<ul>";

            while (reader.Read())
            {
                string sid = (string)reader["sid"];
                string displayName = (string)reader["displayName"];

                lit2.Text += "<li><a href=\"Explorer.aspx?u=" + sid + "\">" + displayName + "</a></li>";
            }

            lit2.Text += "</ul>";

            reader.Close();
            databaseConnection.Close();
        }

        /// <summary>
        /// Checks to see if a the config file has a particular user flagged as an administrator.
        /// </summary>
        /// <param name="logon">
        /// The logon that we are to check.
        /// </param>
        /// <returns>
        /// True if the user is an administrator, false otherwise.
        /// </returns>
        protected static bool IsUserAdministrator(string logon)
        {
            TimesheetSettings timesheetSettings = (TimesheetSettings)ConfigurationManager.GetSection("timesheetSettings");

            // Check the TimesheetAdministrators app settings entry (if it exists) for the logon that was passed
            // to this function
            foreach (TimesheetAdministrator administrator in timesheetSettings.Administrators)
            {
                if (administrator.LoginID.ToLower() == logon.ToLower())
                    return true;
            }
            
            return false;
        }
    }
}
